package cn.eeany.zutools.index.service.impl

import cn.eeany.zutools.index.service.IDbService
import cn.eeany.zutools.index.service.IPathService
import cn.eeany.zutools.index.service.IService
import org.mapdb.DB
import org.mapdb.DBMaker

import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicLong


class MapDb extends ModelService implements IDbService, IService, IPathService {
    Map<String, ConcurrentMap > map = new HashMap<>()
    DB db
    String path

    MapDb(String path, String model) {
        setPath(path)
        setModel(model)
    }

    @Override
    def getDb() {
        if (db == null) {
            db = DBMaker
                    .fileDB("${getPath()}\\${getModel()}.db")
                    .fileMmapEnable()
                    .make();

        }
        return db
    }


    ConcurrentMap  getTable(String kvTable) {
        if (map[kvTable] == null) {
            map[kvTable] = getDb()
                    .hashMap(kvTable)
                    .createOrOpen()
        }
        return map[kvTable]
    }
    def close(){
        this.db?.close()
    }
    @Override
    def setPath(String modelname) {
       this.path=modelname
    }

    @Override
    def getPath() {
        return path
    }

    Long inc(String mykey){
        ConcurrentMap<String, Long> inc =getTable("inc")
        AtomicLong atomicIncNumber
        //读取原来的值
        Long redb = inc.get(mykey)
        if(redb==null) {
            redb = 1
        }
        if (inc.get(mykey) != null) {
            atomicIncNumber = new AtomicLong(redb)
        } else {
            atomicIncNumber = new AtomicLong()
        }
        atomicIncNumber.getAndIncrement()
        long re = atomicIncNumber.get()
        //保存
        inc.put(mykey,re)
        return  re
    }
}
